package com.example.merchantdemo.paymentstart.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.merchantdemo.constants.MerchantInfoConstant;
import com.example.merchantdemo.constants.SecretKeyConstant;
import com.example.merchantdemo.paymentstart.controller.PaymentStartController;
import com.example.merchantdemo.paymentstart.dto.*;
import com.example.merchantdemo.paymentstart.service.SellCoinService;
import com.example.merchantdemo.util.HttpClientUtil;
import com.example.merchantdemo.util.SignatureGenerateHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Objects;

@Service
public class SellCoinServiceImpl implements SellCoinService {

    /**
     * 查询匹配总价(用户卖币，输入数量后，得到预计总价)
     *
     * @param req
     * @return
     */
    @Override
    public PlatformResponse<QueryMatchingTotalPriceResp> queryMatchingTotalPrice(QueryMatchingTotalPriceReq req) {
        System.out.println(JSONObject.toJSONString(req));

        QueryMatchingTotalPriceRequest request = new QueryMatchingTotalPriceRequest();
        BeanUtils.copyProperties(req, request);
        request.setMerchantId(MerchantInfoConstant.MERCHANT_APP_ID);
        // 目前只支持 CNY
        request.setCurrencyName("CNY");
        request.setMerchantSign(SignatureGenerateHelper.generateSign(SecretKeyConstant.MERCHANT_PRIVATE_KEY, request));

        //向支付平台发起查询
        String result = HttpClientUtil.sendHttpPostJson(PaymentStartController.hostAddress +
                        "/pay/v3.1/queryMatchingTotalPrice", Collections.EMPTY_MAP, Collections.EMPTY_MAP,
                JSONObject.toJSONString(request));

        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!Objects.equals(200, jsonObject.getInteger("code"))) {
            throw new RuntimeException(jsonObject.getString("message"));
        }

        QueryMatchingTotalPriceResp resp = jsonObject.getObject("data", QueryMatchingTotalPriceResp.class);
        PlatformResponse response = new PlatformResponse();
        response.setCode(200);
        response.setMessage("调用成功");
        response.setData(resp);

        return response;
    }

    /**
     * 发起卖币
     *
     * @param req
     * @return
     */
    @Override
    public PlatformResponse initialToSellCoin(InitialToSellCoinReq req) {

        // 这里需要根据商户端的用户id，将用户的币冻结，并生成订单，然后再向支付平台发起卖币

        InitialToSellCoinRequest request = new InitialToSellCoinRequest();
        BeanUtils.copyProperties(req, request);
        request.setMerchantId(MerchantInfoConstant.MERCHANT_APP_ID);
        // 目前只支持CNY
        request.setCurrencyName("CNY");
        // 这里需要生成商户端卖币订单号(用商户端自己的订单号生成逻辑)
        request.setMerchantOrderCode("" + System.currentTimeMillis());
        request.setMerchantSign(SignatureGenerateHelper.generateSign(SecretKeyConstant.MERCHANT_PRIVATE_KEY, request));

        // 向支付平台发起卖币
        String result = HttpClientUtil.sendHttpPostJson(PaymentStartController.hostAddress +
                        "/pay/v3.1/initialToSellCoin", Collections.EMPTY_MAP, Collections.EMPTY_MAP,
                JSONObject.toJSONString(request));

        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!Objects.equals(200, jsonObject.getInteger("code"))) {
            throw new RuntimeException(jsonObject.getString("message"));
        }

        JSONObject body = jsonObject.getJSONObject("data");
        InitialToSellCoinResponse response = JSONObject.parseObject(JSONObject.toJSONString(body),
                InitialToSellCoinResponse.class);

        // 对返回参数验签
        Boolean verifyResult = SignatureGenerateHelper.verifyRSASign(SecretKeyConstant.PLATFORM_PUBLIC_KEY,
                JSONObject.toJSONString(body),
                response.getMerchantSign());
        if (!verifyResult) {
            throw new RuntimeException("验签失败");
        }

        InitialToSellCoinResp resp = new InitialToSellCoinResp();
        // 将本次交易商户订单号返回给前端
        resp.setMerchantOrderCode(request.getMerchantOrderCode());
        resp.setUnitPrice(response.getUnitPrice());
        resp.setOrderPrice(response.getOrderPrice());
        resp.setSellAmount(response.getSellAmount());

        PlatformResponse platformResponse = new PlatformResponse();
        platformResponse.setCode(jsonObject.getInteger("code"));
        platformResponse.setMessage(jsonObject.getString("message"));
        platformResponse.setData(resp);

        return platformResponse;
    }

    /**
     * 商户端用户确认收款并放币
     *
     * @param req
     * @return
     */
    @Override
    public PlatformResponse confirmedReceiptAndCoinRelease(ConfirmedReceiptAndCoinReleaseReq req) {

        ConfirmedReceiptAndCoinReleaseRequest request = new ConfirmedReceiptAndCoinReleaseRequest();
        BeanUtils.copyProperties(req, request);
        request.setMerchantId(MerchantInfoConstant.MERCHANT_APP_ID);
        request.setMerchantSign(SignatureGenerateHelper.generateSign(SecretKeyConstant.MERCHANT_PRIVATE_KEY, request));


        // 向支付平台发起确认收款并放币
        String result = HttpClientUtil.sendHttpPostJson(PaymentStartController.hostAddress +
                        "/pay/v3.0/confirmedReceiptAndCoinRelease", Collections.EMPTY_MAP, Collections.EMPTY_MAP,
                JSONObject.toJSONString(request));

        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!Objects.equals(200, jsonObject.getInteger("code"))) {
            throw new RuntimeException(jsonObject.getString("message"));
        }

        // 这里用户确认收到了款，并放币完成后，需要将用户冻结的币扣掉。

        PlatformResponse response = new PlatformResponse();
        response.setCode(jsonObject.getInteger("code"));
        response.setMessage(jsonObject.getString("message"));
        response.setData(new JSONObject());

        return response;
    }

}
